ASP.NET Core MVC 之語系切換


Posted by hotmaneil on 2023-11-22

  1. 新增專案類型:ASP.NET Core Web應用程式
  2. 目標Framework為.NET 7.0
  3. 在Program.cs裡的內加進如下:
var supportedCultures = new List<CultureInfo>()
{
    CultureInfo.GetCultureInfo("en"),
    CultureInfo.GetCultureInfo("zh")
};

app.UseRequestLocalization(new RequestLocalizationOptions()
{
    DefaultRequestCulture = new RequestCulture("zh"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures,
});

其中DefaultRequestCulture = new RequestCulture("zh")為預設中文
4.在專案下新增資料夾Resources並新增SharedResources.cs,SharedResources.en和SharedResources.zh的resx資源檔

SharedResources.cs

namespace Localization
{
    public class SharedResources
    {
    }
}

5.編輯resx的中英文如下:

6.在 _Layout.cshtm 新增如下:

<!-- 自己弄的選取語言下拉選單 -->
<select id="selectLang">
    <option value="zh">中文</option>
    <option value="en">English</option>
</select>
$(function () {
    dropdownListSetLanguage();
    $("#selectLang").on("change", function () {
        changeLanguage();
    });
})

 /** 下拉選單選取的語系 */
 function dropdownListSetLanguage() {

     const urlParams = new URLSearchParams(window.location.search);
     var param = urlParams.get('culture')
     if (param !== null) {
         $("#selectLang").val(param)
     } else {
         var culture = $.cookie('culture');
         $("#selectLang").val(culture)
     }
 }

 /** 變更語系*/
 function changeLanguage() {
     var selectedLang = $("#selectLang").val();

     const urlParams = new URLSearchParams(window.location.search);
     var param = urlParams.get('culture')
     var pathName = $(location).attr('pathname');

     console.log('changeLanguage urlParams:' + urlParams)
     console.log('changeLanguage param:' + param)
     console.log('changeLanguage pathname:' + pathName)

     var url = pathName + "?culture=" + selectedLang;
     window.location.href = url;
 }

7.在Razor套用語系的寫法:

  • 第一種
    HomeController.cs
    public IActionResult Index(string culture)
    {
      ViewData["Login"] = _localizer["Login"];
      return View();
    }
    
    Index.cshtml
    <h5>@ViewData["Login"]</h5>
    
  • 第二種
    Index.cshtml
    @using Microsoft.AspNetCore.Mvc.Localization
    @using Localization
    @inject IHtmlLocalizer<SharedResources> _localizer
    
    <h5>@_localizer["lang"]</h5>
    
    畫面結果如下:


#ASP.NET Core MVC







Related Posts

[筆記] Linux管理、Shell script 簡易範例

[筆記] Linux管理、Shell script 簡易範例

電腦科學概論筆記

電腦科學概論筆記

Hacktoberfest 2020 參與心得分享

Hacktoberfest 2020 參與心得分享


Comments